package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    public <E> List<E> selectList(MappedStatement mappedStatement, Object... params) throws Exception {
        return query(mappedStatement, params);
    }

    public <E> E selectOne(MappedStatement mappedStatement, Object... params) throws Exception {
        List<E> list = this.selectList(mappedStatement, params);
        if (list.size() > 1) {
            throw new RuntimeException("查询的结果不唯一");
        }

        return list.get(0);
    }

    public <E> List<E> query(MappedStatement mappedStatement, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        return executor.query(configuration, mappedStatement, params);
    }

    public <E> E update(MappedStatement mappedStatement, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        return executor.update(configuration, mappedStatement,params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理来为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);


                if ("select".equals(mappedStatement.getNodeType())) {
                    // 准备参数2：params:args
                    // 获取被调用方法的返回值类型
                    Type genericReturnType = method.getGenericReturnType();
                    // 判断是否进行了 泛型类型参数化
                    if (genericReturnType instanceof ParameterizedType) {
                        List<Object> objects = selectList(mappedStatement, args);
                        return objects;
                    }
                    return selectOne(mappedStatement, args);
                }else {
                    return update(mappedStatement, args);
                }
            }
        });
        return (T) proxyInstance;
    }
}